<?php

class SiteReportsEmailsGenerator
{
  protected $_pdo;
    
  public function __construct()
  {   
    $this->_pdo = PDOFactory::getInstance();
  }
  
  public function findNotExisted()
  { 
    $query = $this->_pdo->query(
      'SELECT `sites`.* FROM `sites` '.
      ' LEFT JOIN `sites_reports_emails` ON `sites_reports_emails`.`idSite` = `sites`.`idSite`'.
      ' WHERE'.
      ' `sites_reports_emails`.`idReportEmail` IS NULL'.
      ' AND `sites`.`emailReport` != "" AND  `sites`.`emailReportFreq` > 0'
      );
    $query->setFetchMode(PDO::FETCH_CLASS, 'Site');
    $query->execute();    
    $count = 0;
    foreach( $query as $site ) {
      echo $site->name." (idSite: ".$site->idSite.", to: ".$site->emailReport.", freq: ".$site->emailReportFreq.")\n";
      $this->_createData($site);
      $count++;
    }
    return $count;
  }
  
  public function findOutdated()
  {     
    $query = $this->_pdo->query(
      'SELECT `sites`.*'.
      'FROM `sites` '.
      'LEFT JOIN `sites_reports_emails` ON '.
      '`sites`.`idSite` = `sites_reports_emails`.`idSite` '.
      'AND `sites_reports_emails`.`createdAt` >= DATE_FORMAT(NOW() - INTERVAL (`sites`.`emailReportFreq`-1) DAY, "%Y-%m-%d 00:00:00")'.
      'AND `sites_reports_emails`.`status` = "OK"'.
      'WHERE '.
      ' `sites_reports_emails`.`idReportEmail` IS NULL'.
      ' AND `sites`.`emailReport` != "" AND  `sites`.`emailReportFreq` > 0'
      );
    $query->setFetchMode(PDO::FETCH_CLASS, 'Site');
    $query->execute();    
    $count = 0;
    foreach( $query as $site ) {
      echo $site->name." (idSite: ".$site->idSite.", to: ".$site->emailReport.", freq: ".$site->emailReportFreq.")\n";
      $this->_createData($site);
      $count++;
    }
    return $count;
  }      
  
  protected function _createData($site)
  {
    $data = array(
      'idSite' => $site->idSite,
      'status' => 'ok'
      );
    try {
      $mail = new Mail_Report($site);
      $mail->send();
    } catch( Exception $e ) {
      $data['status'] = 'error';
      $data['error'] = $e->getMessage().' at '.$e->getFile().' ('.$e->getLine().')';
    }
    
    $sql = 'INSERT INTO `sites_reports_emails` (';
    foreach( array_keys($data) as $key ) {
      $sql .= ' `'.$key.'`,';
    }
    $sql = rtrim($sql,',');
    $sql .= ') VALUES (';
    foreach( array_keys($data) as $key ) {
      $sql .= ' :'.$key.',';
    }
    $sql = rtrim($sql,',');
    $sql .= ')';
    $state = $this->_pdo->prepare($sql);
    foreach( $data as $key => $v ) {
      $state->bindValue(':'.$key,$v);
    }
    $state->execute();
  }
}